package com.neouton.crm.supplier.service.impl;

import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.neouton.common.entity.ActivitiVO;
import com.neouton.common.entity.FeeMainVO;
import com.neouton.common.util.*;
import com.neouton.crm.approval.entity.ApprovalVO;
import com.neouton.crm.approval.service.IApprovalService;
import com.neouton.crm.customer.entity.ContactsVO;
import com.neouton.crm.customer.entity.CustomerVO;
import com.neouton.crm.dictionary.entity.DictionaryLookupItemVO;
import com.neouton.crm.dictionary.service.IDictionaryService;
import com.neouton.crm.enterprise.entity.EnterpriseVO;
import com.neouton.crm.enterprise.mapper.EnterpriseMapper;
import com.neouton.crm.entity.SysUserEntity;
import com.neouton.crm.op.entity.SalesOpportunityVO;
import com.neouton.crm.op.mapper.SalesOpportunityMapper;
import com.neouton.crm.payRecords.entity.PaymentRecords;
import com.neouton.crm.payRecords.entity.PaymentRequest;
import com.neouton.crm.payRecords.mapper.PaymentRecordsMapper;
import com.neouton.crm.payRecords.mapper.PaymentRequestMapper;
import com.neouton.crm.paymentPlan.entity.PaymentPlan;
import com.neouton.crm.paymentPlan.mapper.PaymentPlanMapper;
import com.neouton.crm.pm.entity.*;
import com.neouton.crm.pm.mapper.BrAndBmrMapper;
import com.neouton.crm.pm.mapper.ContractInfoMapper;
import com.neouton.crm.pm.mapper.PurchaseOrdeMapper;
import com.neouton.crm.pm.mapper.SalesProjectManageMapper;
import com.neouton.crm.pm.service.BrAndBmrService;
import com.neouton.crm.pm.service.IPurchaseOrdeService;
import com.neouton.crm.receiptRecords.entity.ReceiptRecords;
import com.neouton.crm.receiptRecords.mapper.ReceiptRecordsMapper;
import com.neouton.crm.refundRecords.entity.RefundRecordsVO;
import com.neouton.crm.refundRecords.mapper.RefundRecordsMapper;
import com.neouton.crm.supplier.entity.SupplierVO;
import com.neouton.crm.supplier.mapper.SupplierMapper;
import com.neouton.crm.supplier.service.SupplierService;
import com.neouton.crm.transpondEmail.entity.TranspondEmailVO;
import com.neouton.crm.transpondEmail.mapper.TranspondEmailMapper;
import com.neouton.crm.transpondEmail.service.TranspondEmailService;
import com.neouton.feginClient.FeginService;
import com.neouton.feginClient.ReimburseService;
import com.neouton.feginClient.WorkFlowFeginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;

@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private IDictionaryService dictionaryService;

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private EnterpriseMapper enterpriseMapper;

    @Resource
    private WorkFlowFeginService workFlowFeginService;

    @Resource
    private FeginService feginService;

    @Resource
    private IApprovalService approvalService;

    @Value("${webSit.web}")
    private String webSitUrl;
    /**
     * 多条件分页查询客户信息列表
     * @Timestamp: 2022-11-18
     * @Author: WuJie
     * @param page 分页信息
     * @param supplier 其余查询条件
     * @return 分页查询结果
     */
    @Override
    public PageUtil<SupplierVO> querySupplierByPage(IPage page, SupplierVO supplier, String orderBy){
        IPage<SupplierVO> iPage = supplierMapper.querySupplierByPage(page,supplier,orderBy);
        return new PageUtil(iPage);
    }

    @Resource
    private TranspondEmailMapper transpondEmailMapper;

    /**
     * 新增或更新客户信息
     * @Timestamp: 2022-11-17
     * @Author: WuJie
     * @param supplier 需更新实体
     * @return 成功失败
     */
    @Override
    public Boolean saveOrUpdateSupplier(SupplierVO supplier,String token) {
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setProcessName("供应商管理审批流程");
        activitiVO.setProcessCode("supplier_approval");
        activitiVO.setNextNodeParams("businessAffairs");
        //商务信息
        SysUserEntity businessAffairs = dictionaryService.queryMenuUserIdsByCode("commercialSpecialist").get(0);
        activitiVO.setNextNodeAssignee(businessAffairs.getAccount());
        //售后信息
        SysUserEntity afterSaleManager = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
        //总经理信息
        SysUserEntity generalManager = dictionaryService.queryMenuUserIdsByCode("president").get(0);
        ResponseAPI<ActivitiVO> responseAPI = workFlowFeginService.startMaxVersionProcessByDesignCodeCustomParams(activitiVO);

        supplier.setBusinessId(responseAPI.getResult().getBusinessId());


        ApprovalVO approval = approvalService.initApprovalAndLog(responseAPI.getResult().getBusinessId(),
                Constants.SUPPLIER_TASK_TYPE, supplier.getReason(), "",businessAffairs.getUserId(),"");
        supplier.setApprovalId(approval.getApprovalId());
        supplier.setIsCustomer(Constants.SUPPLIER_NOT_CUSTOMER);
        supplier.setIsDelete(Constants.SUPPLIER_STOP);
        Boolean data;
        if (null == supplier.getSupplierId()) {
            supplier.setCreator(AuthUtils.getUserId());
            supplier.setLastUpdateBy(AuthUtils.getUserId());
            data = supplierMapper.insertSupplier(supplier);
        } else {
            supplierMapper.backSupplierData(supplier);
            supplier.setLastUpdateBy(AuthUtils.getUserId());
            supplier.setAuditOpinion(null);
            data = supplierMapper.updateSupplier(supplier);
        }

        // 转发人记录
        if (supplier.getTranspondUseIdList() != null && supplier.getTranspondUseIdList().size() > 0){
            TranspondEmailVO transpondEmailVO = new TranspondEmailVO();
            transpondEmailVO.setApprovalId(supplier.getApprovalId());
            transpondEmailVO.setTranspondUseIdList(supplier.getTranspondUseIdList());
            transpondEmailMapper.insertTranspondEmailInfo(transpondEmailVO);
        }

        if (businessAffairs.getUserId().equals(AuthUtils.getUserId())){
            //跳过第一步审批
            this.approveSupplier(supplier,token,true);
        }else{
            sendEmailAndPushNotice(businessAffairs,supplier,token);
        }

        return data;
    }

    /**
     * 审批通过
     * @param supplier
     * @param token
     * @return
     */
    @Override
    public Boolean approveSupplier(SupplierVO supplier, String token,Boolean auto) {
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setBusinessId(supplier.getBusinessId());
        //获取当前所处节点
        ResponseAPI<ActivitiVO> processNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);

        //记录审批日志
        if(auto){
            approvalService.insertApprovalLog(supplier.getApprovalId(),"通过",
                    "系统判定跳过",supplier.getAuditOpinion());
        }else {
            //记录日志
            approvalService.insertApprovalLog(supplier.getApprovalId(),"通过",
                    "",supplier.getAuditOpinion());
        }
        if ("商务负责人".equals(processNodeNameAndCode.getResult().getName())){
            // 审批通过
            workFlowFeginService.approvalProcessByBusinessId(activitiVO);
            // 修改供应商状态为启用
            supplierMapper.enableSupplierById(supplier.getSupplierId(),AuthUtils.getUserId());
            approvalService.approved(null,supplier.getApprovalId());
            apSendEmailAndPushNotice(supplier,token);
        }
//        else{
//            SysUserEntity nowApprover;
//            if ("商务负责人".equals(processNodeNameAndCode.getResult().getName())){
//                //售后信息
//                nowApprover = dictionaryService.queryMenuUserIdsByCode("afterSales").get(0);
//                activitiVO.getCustomParams().put("afterSaleManager",nowApprover.getAccount());
//            }else{
//                //总经理信息
//                nowApprover = dictionaryService.queryMenuUserIdsByCode("president").get(0);
//                activitiVO.getCustomParams().put("generalManager",nowApprover.getAccount());
//            }
//            workFlowFeginService.approvalProcessCustomUserByBusinessId(activitiVO);
//            //获取下一节点
//            ResponseAPI<ActivitiVO> nextProcessNodeNameAndCode = workFlowFeginService.getProcessNodeNameAndCode(activitiVO);
//            if(nextProcessNodeNameAndCode.getResult().getAssignee().equals(processNodeNameAndCode.getResult().getAssignee())){ //记录日志
//                this.approveSupplier(supplier,token,true);
//            }else {
//                approvalService.updateNextApproverByApprovalId(nowApprover.getUserId(), supplier.getApprovalId());
//                sendEmailAndPushNotice(nowApprover,supplier,token);
//            }
//        }
        return true;
    }

    /**
     * 审批驳回
     * @param supplier
     * @param token
     * @return
     */
    @Override
    public Boolean rejectionSupplier(SupplierVO supplier, String token) {
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        activitiVO.setBusinessId(supplier.getBusinessId());
        // 删除实例，驳回至起点
        workFlowFeginService.deleteInstance(activitiVO);
        rjSendEmailAndPushNotice(supplier,token);
        approvalService.insertApprovalLog(supplier.getApprovalId(),"驳回",
                "",supplier.getAuditOpinion());
        return approvalService.approvalRejection(null,supplier.getApprovalId());
    }

    @Override
    public List<SupplierVO> selectAllEnterprise() {
        return supplierMapper.selectAllEnterprise();
    }

    @Override
    public List<SupplierVO> selectAllSupplier() {
        return supplierMapper.selectAllSupplier();
    }
    @Override
    public void exportSupplierInfo(HttpServletResponse response, SupplierVO supplier) throws Exception {
        List<SupplierVO> supplierList = supplierMapper.queryAllSupplier(supplier);
        List<String> codes = new ArrayList<>();
        codes.add("rank_correlation");
        codes.add("isSupplierOrIsCustomer");
        codes.add("isDelete");
        // 获取机会状态字典
        String stateDictCode = "approvalStatus";
        List<String> dictCodes = new ArrayList<>();
        dictCodes.add(stateDictCode);
        JSONObject jsonObject = feginService.queryDictionaryLookupInfo("crm", dictCodes);
        LinkedHashMap linkedHashMap = (LinkedHashMap) jsonObject.get("result");
        List<Map> approvalStatus = (List) linkedHashMap.get("approvalStatus");
        Map<String, List<DictionaryLookupItemVO>> stringListMap = dictionaryService.queryDictionaryLookupInfo(null, codes);
        for (int i = 0; i < supplierList.size(); i++) {
            SupplierVO supplierVO = supplierList.get(i);
            supplierVO.setSupplierId(i+1);
            for (DictionaryLookupItemVO dictionaryLookupItemVO:stringListMap.get("rank_correlation")) {
                if(dictionaryLookupItemVO.getItemCode().equals(supplierVO.getRankCorrelation()+"")){
                    supplierVO.setRankCorrelationStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            for (Map item:approvalStatus) {
                if(item.get("itemCode").equals(supplierVO.getStatus()+"")){
                    supplierVO.setStatusStr((String) item.get("itemName"));
                    break;
                }
            }
            for (DictionaryLookupItemVO dictionaryLookupItemVO:stringListMap.get("isSupplierOrIsCustomer")) {
                if(dictionaryLookupItemVO.getItemCode().equals(supplierVO.getIsCustomer()+"")){
                    supplierVO.setIsCustomerStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
            for (DictionaryLookupItemVO dictionaryLookupItemVO:stringListMap.get("isDelete")) {
                if(dictionaryLookupItemVO.getItemCode().equals(supplierVO.getIsDelete()+"")){
                    supplierVO.setIsDeleteStr(dictionaryLookupItemVO.getItemName());
                    break;
                }
            }
        }
        //获取yml模板位置
        YamlPropertiesFactoryBean factoryBean = new YamlPropertiesFactoryBean();
        String path = "application.yml";
        factoryBean.setResources(new ClassPathResource(path));
        Properties properties = factoryBean.getObject();
        String productTemplatePath = String.valueOf(properties.get("report.supplierTemplate"));

        //依据根目录获取模板位置
        TemplateExportParams params = new TemplateExportParams(productTemplatePath);
        Map<String, Object> map = new HashMap<>();
        map.put("supplierInfo",supplierList);
        ReportUtils.exportExcel(params,map,"供应商信息",response);
    }

    @Override
    public Map<String, Object> queryTodoSupplierByApprovalId(Integer approvalId) {
        HashMap<String,Object> res = new HashMap<>();
        res.put("products",supplierMapper.queryTodoSupplierByApprovalId(approvalId));
        res.put("approval",approvalService.queryApprovalByAppID(approvalId));
        return res;
    }

    @Override
    public Map<String, Object> queryTHistorySupplierByApprovalId(Integer approvalId) {
        HashMap<String,Object> res = new HashMap<>();
        List<SupplierVO> supplierVOS = supplierMapper.queryTHistorySupplierByApprovalId(approvalId);
        if (supplierVOS.size()>=1){
            res.put("products",supplierVOS);
        }else{
            res.put("products",supplierMapper.queryTodoSupplierByApprovalId(approvalId));
        }
        res.put("approval",approvalService.queryApprovalByAppID(approvalId));
        return res;
    }

    /**
     * 禁用供应商信息
     * @param approvalId crm审批日志id
     * @return
     */
    @Override
    public Boolean forbiddenCustomerByApplyId(Integer approvalId){
        //获取当前登录人ID
        Integer userId = AuthUtils.getUserId();
        Integer isDelete = Constants.SUPPLIER_STOP;
        Boolean data = supplierMapper.forbiddenCustomerByApplyId(approvalId,userId,isDelete);
        return data;
    }

    /**
     * 禁用供应商信息
     * @param supplierId 需删除的ID
     * @return
     */
    @Override
    public Boolean deleteSupplierById(Integer supplierId){
        Boolean data = supplierMapper.deleteSupplierById(supplierId,AuthUtils.getUserId());
        return data;
    }

    /**
     * 启用供应商信息
     * @param supplierId
     * @return
     */
    public Boolean enableSupplierById(Integer supplierId){
        Boolean data = supplierMapper.enableSupplierById(supplierId,AuthUtils.getUserId());
        return data;
    }

    /**
     * 根据部分条件查询客户信息是否存在
     * @param sp
     * @return
     */
    @Override
    public SupplierVO querySupplier(SupplierVO sp){
        return supplierMapper.querySupplier(sp);
    }
    /**
     * 查询并更改是否为供应商，每次刷新更新
     * @return true成功，false失败
     */
    @Override
    public Boolean selectIsCustomer(){
        Boolean stage = supplierMapper.updateIsCustomer();
        return stage;
    }


    public void sendEmailAndPushNotice(SysUserEntity users,SupplierVO supplier,String token){
        SupplierVO vo = supplierMapper.selectSupplierById(supplier.getSupplierId());
//        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(supplier.getEnterpriseId());
//        SysUserEntity creatorInfo = feginService.searchUserInfoById(supplier.getCreator(), token).getResult();
        //发送邮件
//        String titel = "【系统通知】供应商信息 - 流程单审批通知";
//        String msg = "<div>"
//                + "<p> 尊敬的" + users.getLoginName() + " ：<br></p ></div>"
//                + "<p> &nbsp; &nbsp; &nbsp; 您好，您有一张新的供应商信息审批需要处理：</p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 供应商名称："+enterpriseVO.getEnterpriseName()+"<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 联系人："+vo.getSupplierContacts()+"<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 申请人："+creatorInfo.getLoginName()  + " / " + creatorInfo.getAccount() + "<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 申请时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                "<a href='"+webSitUrl+"/?m=crm&p=todoItems&me=todoApproval'>进入</a></p>"
//                + "<p> &nbsp; &nbsp; &nbsp; APP审批路径：工作台 - 待办审批 - CRM系统</p>"
//                + "<div><p style='text-indent: 2em'>谢谢！</p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
//        StringBuilder emailList = selectCC();
//        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(users.getEmail(),null,titel,msg,token));
        //调用通知接口
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(),  new Timestamp(System.currentTimeMillis()), vo.getCreator(),
                Constants.WORK_STATE_START,Constants.SUPPLIER_TASK_TYPE,users.getUserId(),token));
    }

    public void apSendEmailAndPushNotice(SupplierVO supplier,String token){
        SupplierVO vo = supplierMapper.selectSupplierById(supplier.getSupplierId());
        if (vo.getAuditOpinion() == null || vo.getAuditOpinion().isEmpty()){
            vo.setAuditOpinion("无");
        }
        //获取人员信息
        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(supplier.getCreator(),token);
        SysUserEntity user = res.getResult();
        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(supplier.getEnterpriseId());
        //发送邮件
        String titel = "【系统通知】供应商信息 - 流程单审批通过通知";
        String msg = "<div>"
                + "<p> 尊敬的" + user.getLoginName() + " ：<br></p ></div>"
                + "<p> &nbsp; &nbsp; &nbsp; 您好，您提交的供应商信息已通过：</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 供应商名称："+enterpriseVO.getEnterpriseName()+"<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 联系人："+supplier.getSupplierContacts()+"<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 系统查看路径：客户关系管理系统 - 供应商信息管理 - 供应商信息 " +
                "<a href='"+webSitUrl+"/?m=crm&p=supplier&me=supplierInfo'>进入</a></p>"
                + "<div><p style='text-indent: 2em'>谢谢！</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
        //获取抄送
        StringBuilder emailList = selectCC(supplier);
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),emailList.toString(),titel,msg,token));
        //调用通知接口
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(), new Timestamp(System.currentTimeMillis()), vo.getCreator(),
                Constants.WORK_STATE_STOP,Constants.SUPPLIER_TASK_TYPE,0,token));
    }

    public void rjSendEmailAndPushNotice(SupplierVO supplier,String token){
        SupplierVO vo = supplierMapper.selectSupplierById(supplier.getSupplierId());
        if (vo.getAuditOpinion() == null || vo.getAuditOpinion().isEmpty()){
            vo.setAuditOpinion("无");
        }
        //获取人员信息
        ResponseAPI<SysUserEntity> res = feginService.searchUserInfoByIds(supplier.getCreator(),token);
        SysUserEntity user = res.getResult();
        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(supplier.getEnterpriseId());
        //发送邮件
        String titel = "【系统通知】供应商信息 - 流程单审批驳回通知";
        String msg = "<div>"
                + "<p> 尊敬的" + user.getLoginName() + " ：<br></p ></div>"
                + "<p> &nbsp; &nbsp; &nbsp; 您好，您提交的供应商信息已被驳回：</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 供应商名称："+enterpriseVO.getEnterpriseName()+"<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 联系人："+supplier.getSupplierContacts()+"<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 审批人："+AuthUtils.getUserName()  + " / " + AuthUtils.getUserAccount() + "<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 审批时间："+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+ "<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 审批意见："+vo.getAuditOpinion()+"<p>"
                + "<p> &nbsp; &nbsp; &nbsp; 系统查看路径：客户关系管理系统 - 供应商信息管理 - 供应商信息 " +
                "<a href='"+webSitUrl+"/?m=crm&p=supplier&me=supplierInfo'>进入</a></p>"
                + "<div><p style='text-indent: 2em'>谢谢！</p>"
                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(user.getEmail(),null,titel,msg,token));
        //调用通知接口
        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(),  new Timestamp(System.currentTimeMillis()), vo.getCreator(),
                Constants.WORK_STATE_STOP,Constants.SUPPLIER_TASK_TYPE,0,token));
    }

//    public void rjStageSendEmailAndPushNotice(SysUserEntity users,SupplierVO supplier,String token){
//        SupplierVO vo = supplierMapper.selectSupplierById(supplier.getSupplierId());
//        if (vo.getAuditOpinion() == null || vo.getAuditOpinion().isEmpty()){
//            vo.setAuditOpinion("无");
//        }
//        EnterpriseVO enterpriseVO = enterpriseMapper.selectEnterprise(supplier.getEnterpriseId());
//        //发送邮件
//        String titel = "【系统通知】供应商审批待处理通知";
//        String msg = "<div>"
//                + "<p> 尊敬的" + users.getLoginName() + " ：<br></p ></div>"
//                + "<p> &nbsp; &nbsp; &nbsp; 您好，您有已审批的供应商信息审批被驳回需要处理：</p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 供应商名称："+enterpriseVO.getEnterpriseName() + "<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 联系人："+supplier.getSupplierContacts()+"<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 审批意见："+vo.getAuditOpinion()+"<p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 系统审批路径：客户关系管理系统 - 待办事项 - 待办审批 " +
//                "<a href='"+webSitUrl+"/?m=crm&p=todoItems&me=todoApproval'>进入</a></p>"
//                + "<div><p style='text-indent: 2em'>谢谢！</p>"
//                + "<p> &nbsp; &nbsp; &nbsp; 说明：该邮件为系统自动发送，请勿回复。<p>";
////        StringBuilder emailList = selectCC();
//        CompletableFuture.runAsync(() -> EmailUtils.sentMailByAddressee(users.getEmail(),null,titel,msg,token));
//        //调用通知接口
//        CompletableFuture.runAsync(() -> NoticUtils.pushNotic(vo.getApprovalId(),  new Timestamp(System.currentTimeMillis()), vo.getLastUpdateBy(),
//                Constants.WORK_STATE_START,Constants.SUPPLIER_TASK_TYPE,users.getUserId(),token));
//    }
    @Resource
    TranspondEmailService transpondEmailService;
    public StringBuilder selectCC(SupplierVO supplier){
        //获取抄送人
        List<SysUserEntity> userIds = dictionaryService.queryCcUserIdsByCode("supplierCC");
        StringBuilder emailList = new StringBuilder();
        for (int i = 0; i < userIds.size(); i++) {
            if (userIds.size()-1 == i){
                emailList.append(userIds.get(i).getEmail());
            }else {
                emailList.append(userIds.get(i).getEmail());
                emailList.append(",");
            }
        }
        String stringBuilder = transpondEmailService.selectTranspondEmailStr(supplier.getApprovalId());
        if (stringBuilder.length() > 0 && emailList.length() > 0){
            emailList.append(",");
            emailList.append(stringBuilder);
        }
        if (stringBuilder.length() > 0 && emailList.length() == 0){
            emailList.append(stringBuilder);
        }
        return emailList;
    }

    /**
     * 获取供应商待办列表
     * @param page
     * @param supplier
     * @param orderBy
     * @param token
     * @return
     */
    @Override
    public PageUtil<SupplierVO> getSupplierToDoList(IPage page, SupplierVO supplier, String orderBy, String token){
        //1.调取工作流
        ActivitiVO activitiVO = new ActivitiVO();
        activitiVO.setAuthorization(AuthUtils.getUserAccount());
        ResponseAPI<List<ActivitiVO>> workFlowVoResponseAPI = workFlowFeginService.getTasksByAuthorization(activitiVO);
        List<ActivitiVO> activitiVOS = workFlowVoResponseAPI.getResult();
        if( activitiVOS == null || activitiVOS.size() == 0 ){
            return new PageUtil(new PageDTO());
        }else {
            return new PageUtil(supplierMapper.getSupplierToDoList(page, supplier,orderBy, activitiVOS));
        }
    }


    /**
     * 获取供应商已办列表
     * @param page
     * @param supplier
     * @param orderBy
     * @param token
     * @return
     */
    @Override
    public PageUtil<SupplierVO> getSupplierDoneList(IPage page, SupplierVO supplier,String orderBy,String token){
        return new PageUtil(supplierMapper.getSupplierDoneList(page, supplier,orderBy));
    }


    /**
     * 获取供应商申请记录列表
     * @param page
     * @param supplier
     * @param orderBy
     * @param token
     * @return
     */
    @Override
    public PageUtil<SupplierVO> getSupplierRecordsList(IPage page, SupplierVO supplier,String orderBy,String token){
        Integer userId = AuthUtils.getUserId();
        List<SysUserEntity> userList = new ArrayList<>();
        List<SysUserEntity> authUserIList = dictionaryService.queryAuthUserIdsByCode("approvalRecord");
        boolean result = false;
        for (SysUserEntity user:authUserIList) {
            if (Objects.equals(user.getUserId(), userId)) {
                result = true;
            }
        }
        if (result) {
            userList = feginService.getUserIgnoreFlag(token).getResult();
        } else {
            SysUserEntity user = feginService.searchUserInfoByIds(userId,token).getResult();
            if (user.getIsLeader() == 1) {
                userList = feginService.recursiveQueryAllUserByLeaderId(userId, token).getResult();
            }
            userList.add(user);
        }

        return new PageUtil(supplierMapper.getSupplierRecordsList(page, supplier,orderBy,userList));
    }

    @Resource
    private SalesProjectManageMapper salesProjectManageMapper;

    @Resource
    private SalesOpportunityMapper salesOpportunityMapper;


    @Resource
    private ReimburseService reimburseService;

    @Resource
    private SalesProjectManageMapper projectManageMapper;

    @Resource
    private BrAndBmrMapper brAndBmrMapper;

    @Resource
    private ContractInfoMapper contractInfoMapper;

    @Resource
    private BrAndBmrService brAndBmrService;

    @Resource
    private PurchaseOrdeMapper purchaseOrdeMapper;

    @Resource
    private ReceiptRecordsMapper receiptRecordsMapper;

    @Resource
    private PaymentRecordsMapper paymentRecordsMapper;

    @Resource
    private PaymentRequestMapper paymentRequestMapper;

    @Resource
    private RefundRecordsMapper refundRecordsMapper;

    @Resource
    private PaymentPlanMapper paymentPlanMapper;
    /**
     * 依据供应商ID获取供应商相关信息
     * @param supplierId
     * @return
     */
    @Override
    public SupplierVO querySupplierCorrelationBySupplierID(int supplierId,String token) {
        SupplierVO supplierVO = new SupplierVO();
        // 获取项目相关信息
        List<SalesProjectManageVO> salesProjectManageVOS = salesProjectManageMapper.queryProjectBySupplierId(supplierId);
        salesProjectManageVOS.forEach(opportunity -> opportunity.setTypeName("项目信息"));
        supplierVO.getAllThings().addAll(salesProjectManageVOS);
        supplierVO.setSalesProjectList(salesProjectManageVOS);

        // 获取机会信息
        List<SalesOpportunityVO> salesOpportunityVOS = salesOpportunityMapper.queryOpportunityBySupplierId(supplierId);
        salesOpportunityVOS.forEach(opportunity -> opportunity.setTypeName("机会信息"));
        supplierVO.getAllThings().addAll(salesOpportunityVOS);
        supplierVO.setSalesOpportunityList(salesOpportunityVOS);
        // 整理当前所有项目ID
        List<Integer> project = new ArrayList<>();
        if (salesProjectManageVOS != null && salesProjectManageVOS.size() > 0){
            for (SalesProjectManageVO salesProjectManageVO : salesProjectManageVOS) {
                project.add(salesProjectManageVO.getProjectManageId());
            }
        }
        // 整理当前所有机会ID
        List<Integer> oppo = new ArrayList<>();
        if (salesOpportunityVOS != null && salesOpportunityVOS.size() > 0){
            for (SalesOpportunityVO salesOpportunityVO : salesOpportunityVOS) {
                oppo.add(salesOpportunityVO.getOpportunityId());
            }
        }

        if ((salesOpportunityVOS == null || salesOpportunityVOS.size() == 0) && (salesProjectManageVOS == null || salesProjectManageVOS.size() == 0)){
            return new SupplierVO();
        }

        // 获取采购单信息
        List<PurchaseOrderVO> purchaseOrderVOS = purchaseOrdeMapper.queryPurchaseOrdersByIdListAndSupplierId(project,oppo,supplierId);

        for (PurchaseOrderVO pvo:purchaseOrderVOS) {
            pvo.setPurTypeName("采购订单");
            List<Integer> ids = new ArrayList<>();
            ids.add(pvo.getPurchaseId());
            // 收票记录
            pvo.setReceiptRecords(receiptRecordsMapper.getReceiptRecordsByPurchaseIdAndSupplierId(ids,supplierId));
            // 付款记录
            pvo.setPaymentRecords(paymentRecordsMapper.getPayRecordsByPurchaseIdAndSupplierId(ids,supplierId));
            // 付款申请
            pvo.setPaymentRequests(paymentRequestMapper.getPayRequestByPurchaseOrderIdsAndSupplierId(ids,supplierId));
            // 付款计划
            pvo.setPaymentPlans(paymentPlanMapper.getPayPlanListBypurchaseOrderIdAndSupplierId(ids,supplierId));
            // 退款记录
//            pvo.setRefundRecords(refundRecordsMapper.getRefundRecordsByPurchaseIds(ids));

        }
        supplierVO.setPurchaseOrders(purchaseOrderVOS);
        supplierVO.getAllThings().addAll(purchaseOrderVOS);

        List<PurchaseOrderVO> newPurchaseOrderVOS = purchaseOrdeMapper.queryPurchaseOrdersByIdListAndSupplierId(project, oppo,supplierId);

        if(newPurchaseOrderVOS != null && newPurchaseOrderVOS.size()>0){
            List<Integer> list  = new ArrayList<>();
            for (PurchaseOrderVO purchaseOrderVO: newPurchaseOrderVOS) {
                list.add(purchaseOrderVO.getPurchaseId());
            }
            List<PaymentPlan> paymentPlans = paymentPlanMapper.getPayPlanListBypurchaseOrderIdAndSupplierId(list,supplierId);
            List<PaymentRecords> paymentRecords = paymentRecordsMapper.getPayRecordsByPurchaseIdAndSupplierId(list,supplierId);
            List<ReceiptRecords> receiptRecords = receiptRecordsMapper.getReceiptRecordsByPurchaseIdAndSupplierId(list,supplierId);

            List<PaymentRequest> paymentRequests = paymentRequestMapper.getPayRequestByPurchaseOrderIdsAndSupplierId(list,supplierId);

//            List<RefundRecordsVO> recordsVOS = refundRecordsMapper.getRefundRecordsByPurchaseIds(list);
            // 付款计划
            supplierVO.setPaymentPlans(paymentPlans);
            // 付款记录
            supplierVO.setPaymentRecords(paymentRecords);
            // 收票记录
            supplierVO.setReceiptRecords(receiptRecords);
            // 付款申请
            supplierVO.setPaymentRequests(paymentRequests);
            // 退款记录
//            supplierVO.setRefundRecords(recordsVOS);
            // 未回款项
            List<PurchaseOrderVO> notPay = new ArrayList<>();
            for (PurchaseOrderVO item : newPurchaseOrderVOS) {
                // 采购单总金额
                BigDecimal amount = item.getAmount();
                BigDecimal paySumMoney = BigDecimal.ZERO;
                for (PaymentRecords payItem : paymentRecords) {
                    if (item.getPurchaseId().equals(payItem.getPurchaseOrderId())){
                        // 付款记录付款金额累计
                        paySumMoney = paySumMoney.add(new BigDecimal(payItem.getPaymentMoney()));
                    }
                }
                //采购单总金额 大于 付款记录金额
                if (amount.compareTo(paySumMoney) == 1){
                    item.setNotPayTypeName("未回款项");
                    notPay.add(item);
                }
            }
            supplierVO.setNotPay(notPay);
            supplierVO.getAllThings().addAll(notPay);
            supplierVO.getAllThings().addAll(paymentRecords);
            supplierVO.getAllThings().addAll(receiptRecords);
            supplierVO.getAllThings().addAll(paymentRequests);
            supplierVO.getAllThings().addAll(paymentPlans);
//            supplierVO.getAllThings().addAll(recordsVOS);
        }

        return supplierVO;
    }

    /**
     * 通过供应商ID查询供应商视图信息接口
     * @param supplierId
     * @param token
     * @return
     */
    @Override
    public SupplierVO getSupplierDocumentaryViewInfo(Integer supplierId,String token) {
        SupplierVO supplierDocumentaryViewInfo = supplierMapper.getSupplierDocumentaryViewInfo(supplierId);
        List<String> classfiedCode = new ArrayList<>();
        classfiedCode.add("supplierRankCorrelation");
        Map<String, List<DictionaryLookupItemVO>> dataDictionaryLookupItems = dictionaryService.queryDictionaryLookupInfo(null,classfiedCode);
        List<DictionaryLookupItemVO> rankCorrelation = dataDictionaryLookupItems.get("supplierRankCorrelation");
        for (DictionaryLookupItemVO item : rankCorrelation) {
            if (item.getItemCode().equals(supplierDocumentaryViewInfo.getRankCorrelation().toString())){
                supplierDocumentaryViewInfo.setRankCorrelationName(item.getItemName());
            }
        }
        List<ContactsVO> constantList = new ArrayList<>();
        ContactsVO constants = new ContactsVO();
        constants.setContacts(supplierDocumentaryViewInfo.getSupplierContacts());
        constants.setPhoneNumber(supplierDocumentaryViewInfo.getSupplierContactsPhone());
        constants.setPosition(supplierDocumentaryViewInfo.getSupplierPosition());
        constantList.add(constants);
        supplierDocumentaryViewInfo.setContacts(constantList);
        return supplierDocumentaryViewInfo;
    }
}
